 (function($) {

$.elements = {};

$.elements.prepare = function()
{
	$("#deck").droppable({ drop: $.elements.deck_drop }).disableSelection();
	
	$('body').droppable({ drop:$.elements. body_drop });
}
	
$.elements.loadElements=function(tag)
{
	$.post("./bus/load_elements.php", "tag="  + tag,
	function(data)
	{ 
		for(var item in data.Elements)
			$.elements.createHandElement(data.Elements[item].Id, data.Elements[item].Name);
	});
}

$.elements.combineElements=function($element, $target, ui, newElements)
{
	if($element.parent().attr("id") === "deck")
		$element.remove();
		
	$target.remove();
	
	var  newElement;
	
	for(var item in newElements)
	{
		newElement = newElements[item];
	
		var $onHand = $("#hand>div.element[elementId=" + newElement.Id + "]");
	
		if($onHand.length === 0)
			$onHand = $.elements.createHandElement(newElement.Id, newElement.Name);
		
		$.elements.createDeckElement($onHand, ui);
		
	}
	
}

$.elements.createDeckElement=function($handElement, ui)
{
	$handElement.clone().
		css("position", "fixed").
		css("top", ui.position.top - 8).
		css("left", ui.position.left - 8).
		attr("originalTop", ui.position.top - 8).
		attr("originalLeft", ui.position.left - 8).
		attr('id', 'deckElement' + $handElement.attr('elementId') ).
		attr('elementId', $handElement.attr('elementId') ).
		draggable().
		droppable({ greedy:true, drop: $.elements.element_drop }).
		appendTo("#deck");
}

$.elements.createHandElement=function(id, name)
{
	var html = '<div class="element" id="a'+id+'" elementId="'+id+'">' + name + '</div>';
	
	return $(html).
					appendTo("#hand").
					draggable({
						helper: 'clone'
					});
	
}



$.elements.element_drop=function(event, ui)
{
	var $element= $(ui.draggable);
	
	var e1 = $element.attr('elementId');
     
	var e2 = $(this).attr('elementId');

	var query = "elements[]=" + e1 + "&elements[]=" + e2; 
	
	var $target = $(this);
	
	
	
	$.post("./bus/combine_elements.php", query, function(data)
	{
		if(data.sucess)
		{
			$.elements.combineElements($element, $target, ui, data.Elements);
		}
		else
		{
			
			$element.animate(
			{
				left: $element.attr("originalLeft"), 
				top: $element.attr("originalTop")
			}, 'normal');
			
			$.news.suggest.set($element, $target);
			
		}
	});
}

$.elements.deck_drop=function(event, ui)
{
	var $element = $(ui.draggable);

	$element.draggable({ revert: false });
	
	if($element.parent().attr("id") == "hand")
		$.elements.createDeckElement($element, ui);
}

$.elements.body_drop=function(event, ui)
{
	var $item = $(ui.draggable);
	
	if($item.parent().attr('id') == "#deck")
		$item.remove();	
	else
		$item.draggable({ revert: true });
}

$.elements.clear =function()
{
	$("#hand .element").remove();
	
	$("#deck .element").remove();
}

})(jQuery);
	
